import {websocketStore} from "../stores/websokcet";
let url = "ws://127.0.0.1:8004/ws";  //请求的后端地址

interface socket {
    websocket:any
    init: () => any
    send: (e) => void
}

const socket: socket ={
    websocket: null,
    init:()=>{
        socket.websocket = new WebSocket(url);
        // 1  onmessage 获取后台消息
        socket.websocket.onmessage = (e: any) => {

            let data = JSON.parse(e.data)

            console.log("onmessage ")
            // console.log(e)
            console.log(data)

            // 3 是视频通话
            if (data.type == 3){
                window.location.href = "/item?from="+data.from+"&type=2"
            }else {
                const web = websocketStore();
                web.msg = e.data
            }

        }
        // 2 onclose 页面刷新的时候 和 后台websocket服务关闭的时候
        // 3 onopen  获取当前文件状态
        socket.websocket.onclose = (e: any)=>{
        }
    },

    send:(e)=>{
        if (socket.websocket.readyState === 0){
            // 设置延迟
            setTimeout(()=>{
                socket.websocket.send(JSON.stringify(e))
            },1000);
        }else {
            socket.websocket.send(JSON.stringify(e))
        }

    }
}

export default socket
